今天介紹獲取本機網路流量並將其儲存的Python程式.
網路流量一向是系統人員關心的數據,市面上也有許許多多工具,
可以獲得以及繪圖,若自己也能開發此種程式,繪製符合自己需求
的圖形,對系統管理有莫大助益.
首先是建立RRD File的程式.
#!/usr/bin/env python
# ---------------------------------
# Python RRDTool
# Create Network RRD
# ---------------------------------
import rrdtool
rrdtool.create(
'net.rrd', '--step', '60',
'DS:net0_bytes_in:COUNTER:120:0:U',
'DS:net0_packs_in:COUNTER:120:0:U',
'DS:net0_error_in:COUNTER:120:0:U',
'DS:net0_bytes_out:COUNTER:120:0:U',
'DS:net0_packs_out:COUNTER:120:0:U',
'DS:net0_error_out:COUNTER:120:0:U',
'RRA:AVERAGE:0.5:1:2880',
'RRA:AVERAGE:0.5:30:672',
'RRA:AVERAGE:0.5:60:744',
'RRA:AVERAGE:0.5:720:732',
'RRA:MAX:0.5:1:2880',
'RRA:MAX:0.5:30:672',
'RRA:MAX:0.5:60:744',
'RRA:MAX:0.5:720:732',
'RRA:MIN:0.5:1:2880',
'RRA:MIN:0.5:30:672',
'RRA:MIN:0.5:60:744',
'RRA:MIN:0.5:720:732',
'RRA:LAST:0.5:1:2880',
'RRA:LAST:0.5:30:672',
'RRA:LAST:0.5:60:744',
'RRA:LAST:0.5:720:732')
執行以後會建立 rrd 檔.
再來就是獲取本機網路流量的程式.
#!/usr/bin/env python
# -----------------------
# Python RRDTool
# Update Network RRD
# -----------------------
import rrdtool
import time
def get_net0():
"""get net0 data """
net0_dict = {}
item_list = ('rx_bytes', 'rx_packets', 'rx_errors',
'tx_bytes', 'tx_packets', 'tx_errors')
with open('/proc/net/dev', 'r') as nets:
nets_data = nets.readlines()
net0_data = nets_data[-1]
net0_list = net0_data.split()
inet_name = net0_list[0]
inet_name = inet_name.split(':')[0]
rx_bytes = int(net0_list[1])
rx_packets = int(net0_list[2])
rx_errors = int(net0_list[3])
tx_bytes = int(net0_list[9])
tx_packets = int(net0_list[10])
tx_errors = int(net0_list[11])
net0_dict = dict(zip(item_list,
(rx_bytes, rx_packets, rx_errors,
tx_bytes, tx_packets, tx_errors)))
return net0_dict
#
def update_net_rrd(rrdfile):
""" Update net rrd file"""
net_dict = get_net0()
rx_bytes = net_dict['rx_bytes']
rx_packets = net_dict['rx_packets']
rx_errors = net_dict['rx_errors']
tx_bytes = net_dict['tx_bytes']
tx_packets = net_dict['tx_packets']
tx_errors = net_dict['tx_errors']
rrdtool.update(rrdfile, 'N:' + `rx_bytes` + ':' + `rx_packets` \
+ ':' + `rx_errors` + ':' + `tx_bytes` + ':' \
+ `tx_packets` + ':' + `tx_errors`)
#
if __name__ == '__main__':
while 1:
update_net_rrd('net.rrd')
time.sleep(60)
放到背景執行,會每分鐘更新資料,接著讓子彈飛~~~
明天再來繪圖.